<template>
  <div id="discount">
    <div class="center-wrapper">
      <!-- back part -->
      <div class="back-part">
        <div class="back-btn" @click="goBack">
          <img src="@/assets/images/pc_black/auth/back.png" />
          <span>返回</span>
        </div>
      </div>

      <!-- discount info part -->
      <div class="discount-tabbar-part">
        <div class="tab_box">
          <button
            :ref="'tab' + tab.keyword"
            class="tab-btn"
            :class="{ 'green-color': tab.keyword === currentTab }"
            v-for="tab in tabbars"
            :key="tab.keyword"
            @click="tabClick(tab.keyword)"
          >
            {{ tab.name }}
          </button>

          <!-- <i ref="tab_line" class="tab_line"></i> -->
        </div>

        <!-- <el-tabs v-model="currentTab" @tab-click="tabClick">
          <el-tab-pane
            v-for="tab in tabbars"
            :key="tab.keyword"
            :label="tab.name"
            :name="tab.keyword"
          ></el-tab-pane>
        </el-tabs> -->
      </div>

      <!-- discount content part -->
      <div class="discount-content-part">
        <!-- pc card -->
        <template v-if="!isPhone">
          <discount-card
            v-for="cardDetail in cardDetails"
            :key="cardDetail.id"
            :cardDetail="cardDetail"
            @handleExchangeClick="handleExchangeClick"
            :status="status"
            :show_url="show_url"
          ></discount-card>
        </template>

        <!-- mobile card -->
        <template v-else>
          <mescroll-vue
            ref="mescroll"
            :down="mescrollDown"
            :up="mescrollUp"
            @init="mescrollInit"
          >
            <mobile-discount-card
              v-for="cardDetail in cardDetails"
              :key="cardDetail.id"
              :cardDetail="cardDetail"
              @handleExchangeClick="handleExchangeClick"
              :status="status"
              :show_url="show_url"
            ></mobile-discount-card>
          </mescroll-vue>
        </template>

        <div class="noneTip" v-if="cardDetails.length <= 0">
          <img
            class="noneTip_img"
            src="@/assets/images/mobile_black/center/null.png"
          />
          <div class="noneTip_txt">暂无数据</div>
        </div>
      </div>

      <!-- discount pag part-->
      <div class="discount-pag-part" v-if="cardDetails.length > 0">
        <el-page
          @handleCurrentChange="handleCurrentChange"
          :total="total"
          :pageSizes="[4]"
        ></el-page>
      </div>

      <!-- confirm exchange dialog -->
      <el-dialog
        class="exchangeDialog"
        :visible="isShowExchangeDialog"
        top="33vh"
        center
        :before-close="closeExchangeDialog"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <div class="dialog_title">
          <img
            @click="closeExchangeDialog"
            src="@/assets/images/pc_black/auth/close.png"
          />
        </div>

        <div class="dialog_center">
          <p class="center_content">
            是否兑换该优惠券，兑换后可在未使用列表中查看
          </p>
          <div class="dialog_btn">
            <button @click="confirmExchangeClick">是</button>
            <button @click="cancelExchangeClick">否</button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// --- other ---
import MescrollVue from "mescroll.js/mescroll.vue";

// --- components ---
import DiscountCard from "./components/DiscountCard.vue";
import MobileDiscountCard from "./components/MobileDiscountCard.vue";
import ElPage from "@/components/ElPagination.vue";
// --- utils ---
import { iscode, isPhone, animalAction } from "@/utils";
// --- api ---
import { exchangeListApi, doExchangeApi } from "@/api";
// --- vuex ---
import { mapState } from "vuex";

export default {
  name: "Discount",
  components: { DiscountCard, MobileDiscountCard, ElPage, MescrollVue },
  data() {
    return {
      // tabbar按钮显示数据
      tabbars: [
        { keyword: "Exchange", name: "兑换" },
        { keyword: "NotUsed", name: "未使用" },
        { keyword: "Used", name: "已使用" },
        { keyword: "Expired", name: "已过期" },
      ],
      // tabbar当前选中
      currentTab: "Exchange",
      // discountCard数据
      cardDetails: [],
      // 总条数
      total: 0,
      // 每页条数
      pageSize: 4,
      // 当前页数
      currentPage: 1,
      // 是否是移动端
      isPhone: false,
      // 当前状态值
      status: 1,
      // 第三方上拉加载插件数据
      mescroll: null, // mescroll实例对象
      mescrollDown: { use: false }, //下拉刷新的配置. (如果下拉刷新和上拉加载处理的逻辑是一样的,则mescrollDown可不用写了)
      mescrollUp: {
        auto: false,
        // 上拉加载的配置.
        callback: this.upCallback, // 上拉回调,此处简写; 相当于 callback: function(page, mescroll) { }
        page: {
          num: 0, //当前页 默认0,回调之前会加1; 即callback(page)会从1开始
          size: 4, //每页数据条数,默认10
        },
        htmlNodata:
          '<p class="upwarp-nodata" style="display:none;font-size: 0.14583rem;font-family: Microsoft YaHei;font-weight: 600;color: #808080;">-- 没有更多了 --</p>',
        htmlLoading:
          '<p class="upwarp-progress mescroll-rotate"></p><p class="upwarp-tip" style="font-size: 0.14583rem;font-family: Microsoft YaHei;font-weight: 600;color: #808080;">加载中..</p>',
        noMoreSize: 1, //如果列表已无数据,可设置列表的总数量要大于5才显示无更多数据;
        isBounce: false,
      },
      // 是否显示弹窗
      isShowExchangeDialog: false,
      // 兑换卡片的id
      exchangeID: "",
      // show_url for mobile
      show_url: "",
    };
  },
  computed: {
    // 用户信息
    ...mapState(["userInfo"]),
  },
  methods: {
    // ------ 请求相关 ------
    // 获取兑换列表
    async exchangeList() {
      let res = await exchangeListApi({
        page: this.currentPage,
        pagesize: this.pageSize,
        status: this.status, // 1 Exchange, 2 NotUsed, 3 Used, 4 Expired
      });
      if (iscode(res)) {
        const resData = res.result;
        this.total = resData.count;
        this.cardDetails = resData.list;
        this.show_url = res.result.show_url;
        // this.cardDetails.map(item => {
        //   if (this.status === 1) {
        //     this.$set(item, "image", resData.show_url + item.images[0]);
        //   } else {
        //     this.$set(item, "image", resData.show_url + item.icon);
        //   }
        // });
      }
    },
    // 获取兑换列表 status:1
    async firstExchangeList() {
      let res = await exchangeListApi({
        page: this.currentPage,
        pagesize: this.pageSize,
        status: 1, // 1 Exchange, 2 NotUsed, 3 Used, 4 Expired
      });
      if (iscode(res)) {
        if (res.result.count === 0) {
          this.currentTab = "NotUsed";
          this.status = 2;
          this.exchangeList();
        }
      }
    },
    // 上拉加载触发
    async upCallback(page, mescroll) {
      this.mescroll = mescroll;
      let res = await exchangeListApi({
        page: page.num,
        pagesize: page.size,
        status: this.status, // 1 Exchange, 2 NotUsed, 3 Used, 4 Expired
      });
      if (iscode(res)) {
        let resData = res.result.list;
        this.show_url = res.result.show_url;
        // if (res.result.count > 0) {
        //   resData.map(item => {
        //     this.$set(item, "image", res.result.show_url + item.images[0]);
        //   });
        // }
        // 如果是第一页需手动置空列表◊
        if (page.num === 1) {
          this.cardDetails = [];
        }
        // 把请求到的数据添加到列表
        this.cardDetails = [...this.cardDetails, ...resData];

        // 数据渲染成功后,隐藏下拉刷新的状态
        this.$nextTick(() => {
          this.mescroll.endSuccess(resData.length);
        });
      }
    },
    // 兑换
    async doExchange() {
      let res = await doExchangeApi({ id: this.exchangeID });
      if (iscode(res)) {
        if (isPhone()) {
          this.$toast("兑换成功");
        } else {
          this.$message({
            message: "兑换成功",
            iconClass: "mySuccessIcon",
            customClass: "mySuccess",
          });
        }
        this.exchangeList();
      }
      this.closeExchangeDialog();
    },

    // ------  tabbar相关  ------
    // 点击切换tabar
    tabClick(keyword) {
      // 解决重复点击
      if (this.currentTab === keyword) return;
      // 切换赋值（用于active样式）
      this.currentTab = keyword;
      // 触发下划线动画
      // this.tabLineMove(
      //   this.$refs[`tab${keyword}`][0].offsetLeft + (isPhone() ? 8 : 18)
      // );
      this.cardDetails = [];

      // 根据赋值类型调用请求函数
      switch (keyword) {
        case "Exchange":
          this.status = 1;
          break;
        case "NotUsed":
          this.status = 2;
          break;
        case "Used":
          this.status = 3;
          break;
        case "Expired":
          this.status = 4;
          break;
        default:
          break;
      }
      this.exchangeList();
    },
    // #region 触发tab下划线缓动动画
    // tabLineMove(target) {
    //   this.$nextTick(() => {
    //     animalAction(this.$refs.tab_line, target);
    //   });
    // },
    // #endregion

    // ------ dialog相关 ------
    // 打开兑换弹窗
    openExchangeDialog() {
      this.isShowExchangeDialog = true;
    },
    // 关闭兑换弹窗
    closeExchangeDialog() {
      this.exchangeID = ""; // 清除放弃兑换的代金券id
      this.isShowExchangeDialog = false;
    },
    // 响应子组件打开兑换弹窗
    handleExchangeClick(id) {
      this.exchangeID = id; // 存储对应的代金券id
      this.openExchangeDialog();
    },
    // 确认兑换按钮：触发确认兑换接口，并关闭弹窗
    confirmExchangeClick() {
      this.doExchange();
    },
    // 取消兑换按钮：触发关闭弹窗
    cancelExchangeClick() {
      this.closeExchangeDialog();
    },

    // ------ pag相关 ------
    // 点击切换页数
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.exchangeList();
    },

    // ------ mecsroll相关 ------
    // 初始化组件实例，可获取到mescroll对象
    mescrollInit(mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },

    // ------ 跳转相关 ------
    // 返回上一级
    goBack() {
      history.back();
    },
  },
  created() {
    // 判断是否是移动端
    this.isPhone = isPhone();
    this.exchangeList();
    this.firstExchangeList();
  },
  beforeDestroy() {
    let cardCount = JSON.parse(localStorage.getItem("cardCount"));
    cardCount.coupon_num = this.userInfo.coupon_num;
    localStorage.setItem("cardCount", JSON.stringify(cardCount));
  },
};
</script>

<style lang="less" scoped>
#discount {
  min-height: 991px;

  // center wrapper
  .center-wrapper {
    width: 1200px;
    margin: 0 auto;
    overflow: hidden;
  }

  // back part
  .back-part {
    width: 100%;
    padding-top: 20px;

    .back-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 104px;
      height: 30px;
      border: none;
      background: none;
      background-image: url("../../../assets/images/personalCenter/btn.png");
      background-position: center center;
      background-size: 100% 100%;
      cursor: pointer;

      img {
        width: 20px;
        height: 6px;
      }

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 12px;
        margin-left: 10px;
      }
    }
  }

  // discount tabbar part
  .discount-tabbar-part {
    display: flex;
    align-items: center;
    width: 100%;
    height: 60px;
    // background-color: #2b2c2d;
    margin-top: 30px;

    .tab-btn {
      position: relative;
      background: none;
      border: none;
      width: 80px;
      height: 30px;
      border-radius: 2px;
      // border: 1px solid #999999;
      backdrop-filter: blur(3px);
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #999999;
      line-height: 14px;
      margin-left: 40px;
      background: #2e2f2f;
      transition: all 0.2s ease;
      cursor: pointer;
    }
    .tab-btn:nth-child(1) {
      margin-left: 0;
    }
    // .tab-btn:hover {
    //   color: #ffffff;
    //   // border-color: #ffffffaa;
    // }
    // .tab-btn:active {
    //   color: #00ffb0;
    //   // border-color: #00ffb0;
    // }

    // .tab_box {
    //   position: relative;
    //   display: flex;

    //   .tab_line {
    //     position: absolute;
    //     bottom: -3px;
    //     left: 60px;
    //     width: 43px;
    //     height: 2px;
    //     background-color: #00ffb0;
    //   }
    // }
  }

  // discount content part
  .discount-content-part {
    width: 100%;
    height: 540px;
    margin-top: 20px;
    margin-bottom: 20px;

    // 数据空时的提示语
    .noneTip {
      text-align: center;
      margin-top: 30px;
      font-size: 20px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: bold;
      opacity: 0.6;
    }

    .noneTip_txt {
      width: 100%;
      font-size: 14px;
      color: #999;
      margin-top: 20px;
      text-align: center;
    }

    .noneTip_img {
      width: 260px;
    }
  }

  // discount pag part
  .discount-pag-part {
    display: flex;
    justify-content: center;
    width: 100%;
  }

  // exchange dialog
  .exchangeDialog {
    /deep/.el-dialog {
      max-width: 460px;
      height: 220px;
      background: #1e2020;
      border-radius: 10px;

      .el-dialog__header {
        display: none;
      }
      .el-dialog__body {
        margin: 0;
        padding: 0;

        .dialog_title {
          display: flex;
          justify-content: flex-end;
          width: 100%;
          padding: 30px 30px 0 0;

          img {
            width: 16px;
            height: 16px;
            cursor: pointer;
          }
        }
        .dialog_center {
          position: relative;
          width: 100%;
          padding-top: 25px;

          .center_content {
            font-size: 18px;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #ffffff;
            line-height: 18px;
            text-align: center;
          }

          .dialog_btn {
            display: flex;
            justify-content: space-between;
            margin-top: 50px;
            padding: 0 75px;

            button {
              width: 96px;
              height: 32px;
              border-radius: 3px;
              font-size: 14px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              line-height: 14px;
              cursor: pointer;
            }
            button:nth-child(2) {
              background: #1e2020;
              border: 1px solid #666666;
              color: #999999;
            }
            button:nth-child(1) {
              background: #00ffb0;
              border: none;
              color: #1e2020;
            }
          }
        }

        // 双击不选中
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        -khtml-user-select: none;
        user-select: none;
      }
    }
  }

  /deep/.el-dialog__wrapper {
    background: rgba(0, 0, 0, 0.8);
  }

  // public style
  // - 主题绿色
  .green-color {
    color: #1c1e1e !important;
    background: #00ffb0 !important;
  }
  // - 0.5透明度
  .opacity-half {
    opacity: 0.5 !important;
  }
}

@media screen and (max-width: 768px) {
  #discount {
    .center-wrapper {
      width: 100%;
      overflow: visible;
      height: auto;
    }

    .back-part,
    .discount-pag-part {
      display: none;
    }

    .discount-tabbar-part {
      display: flex;
      align-items: center;
      // justify-content: center;
      width: 100%;
      height: 120px;
      // background-color: #2b2c2d;
      margin: 0;
      padding: 0;
      // box-shadow: 0 2px 2px 0 black;
      padding-left: 20px;

      .tab-btn {
        // display: flex;
        // justify-content: center;
        // align-items: center;
        width: 120px;
        height: 60px;
        font-size: 28px;
        word-break: keep-all;
        padding: 0;
      }
      .tab-btn:first-child {
        margin-left: 0;
      }

      // .tab_box {
      //   .tab_line {
      //     bottom: 0;
      //     left: 15px;
      //     width: 88px;
      //     height: 3px;
      //   }
      // }
    }

    .discount-content-part {
      width: 100%;
      height: auto;
      margin-top: 20px;
      // padding-bottom: 20px;
      overflow: scroll;

      // 数据空时的提示语
      .noneTip {
        margin-top: 60px;
      }

      .noneTip_txt {
        font-size: 28px;
        margin-top: 20px;
      }

      .noneTip_img {
        width: 420px;
      }
    }

    // exchange dialog
    .exchangeDialog {
      /deep/.el-dialog {
        max-width: 650px;
        width: 650px;
        height: 370px;
        .el-dialog__body {
          .dialog_title {
            padding: 30px 30px 0 0;

            img {
              width: 30px;
              height: 30px;
            }
          }
          .dialog_center {
            padding-top: 50px;

            .center_content {
              padding: 0 20px;
              font-size: 30px;
              line-height: 40px;
            }

            .dialog_btn {
              margin-top: 80px;
              padding: 0 70px;

              button {
                width: 190px;
                height: 64px;
                font-size: 28px;
                line-height: 28px;
              }
            }
          }
        }
      }
    }
  }

  /*通过fixed固定mescroll的高度*/
  .mescroll {
    position: fixed;
    left: 0;
    top: 215px;
    bottom: 0;
    height: auto;
    padding: 0 20px;
  }
}
</style>
